package com.easy.framework;

import com.alicp.jetcache.Cache;
import com.alicp.jetcache.anno.CreateCache;
import com.easy.common.constant.RegularExpression;
import com.easy.common.core.domain.entity.User;
import com.easy.common.core.domain.model.RegisteredBody;
import com.easy.common.enums.UserStatus;
import com.easy.user.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

import static com.easy.common.constant.ResultConstant.*;

/**
 * 用户 验证 处理
 *
 * @author RuoYu
 * @date 2022/11/19
 */
@Component
public class UserVerify {
    private static final Logger log = LoggerFactory.getLogger(UserVerify.class);

    @Autowired
    private UserService userService;


/*    @CreateCache(area = "userLogin", name = "try", expire = 500, timeUnit = TimeUnit.SECONDS)
    private Cache<String, User> login;*/

    @CreateCache(area = "email", name = "ord_user_", expire = 300, timeUnit = TimeUnit.SECONDS)
    private Cache<String, String> emailCache;

    public String quickByAccount(String account) {
        boolean phone = account.matches(RegularExpression.PHONE_PATTERN);
        boolean mail = account.matches(RegularExpression.MAIL_PATTERN);
        String msg = null;
        if (phone) {/*手机号*/
            log.info("手机号登录校验:{}", account);
            User user = userService.selectByUserPhone(account);
            if (user == null) {
                msg = UserStatus.OK.getCode();
            } else {
                msg = common2(user, account);
            }
        } else if (mail) {/*邮箱*/
            log.info("邮箱登录校验:{}", account);
            User user = userService.selectByUserEmail(account);
            if (user == null) {
                msg = UserStatus.OK.getCode();
            } else {
                msg = common2(user, account);
            }
        }
        return msg;
    }

    /**
     * 用户帐户
     *
     * @param account 账户(用户名/手机号/邮箱)
     * @return {@link String}
     */
    public String loadUserByAccount(String account) {
        boolean phone = account.matches(RegularExpression.PHONE_PATTERN);
        boolean mail = account.matches(RegularExpression.MAIL_PATTERN);
        String msg;
        if (phone) {/*手机号*/
            log.info("手机号登录校验:{}", account);
            User user = userService.selectByUserPhone(account);
            if (user == null) {
                msg = UserStatus.OK.getCode();
            } else {
                msg = common(user, account);
            }
        } else if (mail) {/*邮箱*/
            log.info("邮箱登录校验:{}", account);
            User user = userService.selectByUserEmail(account);
            if (user == null) {
                msg = UserStatus.OK.getCode();
            } else {
                msg = common(user, account);
            }
        } else {/*用户名*/
            log.info("用户名登录校验:{}", account);
            User user = userService.selectUserByUserName(account);
            msg = common(user, account);
        }
        return msg;
    }

    private static String common(User user, String account) {

        System.out.println(user.getStatus()+"----------------------"+UserStatus.DELETED.getCode().equals(user.getDelFlag()));
        System.out.println(UserStatus.DELETED.getCode());
        if (user == null) {
            log.info("登录用户：{} 不存在.", account);
            return "登录用户：" + account + " 不存在";
        } else if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
            log.info("登录用户：{} 已被删除.", account);
            return "对不起，您的账号：" + account + " 已被删除";
        } else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            log.info("登录用户：{} 已被停用.", account);
            return "对不起，您的账号：" + account + " 已停用";
        } else if (UserStatus.ANOMALY.getCode().equals(user.getStatus())) {
            log.info("登录用户：{} 登录异常暂时无法登录.", account);
            return "对不起，您的账号：" + account + " 登录异常暂时无法登录，可以通过发送验证码登录！";
        }
        return UserStatus.OK.getCode();
    }

    private static String common2(User user, String account) {
        if (user == null) {
            log.info("登录用户：{} 不存在.", account);
            return "登录用户：" + account + " 不存在";
        } else if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
            log.info("登录用户：{} 已被删除.", account);
            return "对不起，您的账号：" + account + " 已被删除";
        } else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            log.info("登录用户：{} 已被停用.", account);
            return "对不起，您的账号：" + account + " 已停用";
        }
        return UserStatus.OK.getCode();
    }

    /**
     * 注册 验证
     *
     * @param registeredBody 注册机构
     * @return boolean
     */
    public String registeredVerify(RegisteredBody registeredBody) {
        // 1. 校验用户名是否存在
        boolean b = userService.checkUserName(registeredBody.getUsername());
        if (b) {
            return USER_BEEN_REGISTERED;
        }

        // 2. 校验手机号（邮箱号）是否存在
        boolean phone = registeredBody.getUnique().matches(RegularExpression.PHONE_PATTERN);
        boolean mail = registeredBody.getUnique().matches(RegularExpression.MAIL_PATTERN);

        if (phone) {
            boolean phone_flag = userService.checkUserPhone(registeredBody.getUnique());
            if (phone_flag) {
                return PHONE_BEEN_REGISTERED;
            } else {

            }
        } else if (mail) {
            boolean mail_flag = userService.checkUserEmail(registeredBody.getUnique());
            if (mail_flag) {
                return EMAIL_BEEN_REGISTERED;
            } else {
                String email = registeredBody.getUnique();
                String code = emailCache.get(email);
                log.info("code：{}", code);
                // 3. 校验验证码是否正确
                if (code == null || code.length() <= 0 || !code.equals(registeredBody.getMessageCode())) {
                    return VERIFICATION_CODE_ERROR;
                }
            }
        }
        // 4. 清除验证码缓存
        emailCache.remove(registeredBody.getUnique());
        // 5. 返回可以注册标识
        return "OK";
    }

}
